﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Wizard.Data
{

    public class DataCache
    {
        private Dictionary<string, WeakRef<CacheableObject>>mCachedObjects;

        internal DataCache()
        {
            mCachedObjects = new Dictionary<string, WeakRef<CacheableObject>>();
        }

        internal T Get<T>(string dataStoreId) where T : CacheableObject, new()
        {
            WeakRef<CacheableObject> wr;
            T result = null;
            if (mCachedObjects.TryGetValue(dataStoreId, out wr)) result = wr.Target as T;
            if (result==null)
            {
                result=new T();
                result.mDataStoreId=dataStoreId;
                mCachedObjects[dataStoreId]=new WeakRef<CacheableObject>(result);
            }
            return result;
        }

        internal void Set<T>(T value) where T : CacheableObject, new()
        {
            if (value.mDataStoreId == null) throw new Exception("Cannot cache unkeyed objects");
            mCachedObjects[value.mDataStoreId] = new WeakRef<CacheableObject>(value);
        }

        internal void Clear<T>(T value) where T : CacheableObject, new()
        {
            mCachedObjects[value.mDataStoreId] = null;
        }
    }
}
